package com.ruitaowang.wap;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class APIWapCompanyController extends BaseController {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Autowired
    private CompanyService companyService;
    @Autowired
    private ShoppingOrderService shoppingOrderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CompanyTypeService companyTypeService;
    @Autowired
    private CompanyIndustryService companyIndustryService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CompanyAnnouncementService companyAnnouncementService;


    /**
     * 店铺主页信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/companyDetail")
    public String companyDetail(@RequestHeader(value = "headId", required = false) Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        Company company = companyService.selectByCompanyStaff(userId);
        Company company1 = companyService.selectByUserId(userId);
        if (!ObjectUtils.isEmpty(company)) {
            ShoppingOrder shoppingOrder1 = new ShoppingOrder();
            shoppingOrder1.setCompanyId(company.getCompanyId());
            shoppingOrder1.setRstatus((byte)0);
            shoppingOrder1.setPayStatus((byte)0);
            List<ShoppingOrder> shoppingOrderList = shoppingOrderService.select(shoppingOrder1);
            for (ShoppingOrder s : shoppingOrderList){
                Long sxtime = (System.currentTimeMillis()-s.getCtime())/1000/60;
                if(sxtime >= 30){
                    shoppingOrderService.delete(s.getId());
                    orderService.delete(s.getOrderId());
                }
            }
            ShoppingOrder shoppingOrder = new ShoppingOrder();
            shoppingOrder.setCompanyId(company.getCompanyId());
            shoppingOrder.setPayStatus((byte)0);
            //未付款个数
            Long noPayCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
            shoppingOrder.setPayStatus((byte)1);
            shoppingOrder.setOrderStatus((byte)0);
            //待发货数量
            Long waitPayCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
            shoppingOrder.setOrderStatus((byte)1);
            //已发货数量
            Long PayCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
            shoppingOrder.setOrderStatus((byte)3);
            //售后数量
            Long salePayCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
            shoppingOrder.setOrderStatus((byte)2);
            //订单完成数量
            Long finishPayCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
            //今日开始时间
            Long stime = TimeUtils.getLongDayBegin();
            //今日结束时间
            Long etime = TimeUtils.getLongDayEnd();
            ShoppingOrderVO shoppingOrderVO = new ShoppingOrderVO();
            shoppingOrderVO.setStime(stime);
            shoppingOrderVO.setEtime(etime);
            shoppingOrderVO.setCompanyId(company.getCompanyId());
            //今日成交金额
            Long todayMoeny = shoppingOrderService.todayMoeny(shoppingOrderVO);
            //今日访客
            Long visitor = (long)0;
            //咨询人数
            Long consultation = (long)0;
            //成交订单
            Long orderSuccess = shoppingOrderService.orderSuccess(shoppingOrderVO);
            //商品管理
            Goods goods = new Goods();
            goods.setGoodsProviderId(company.getCompanyId());
            //所有商品
            Long allGoods = goodsService.count(goods);
            goods.setGoodsOnline((byte)1);
            //在售中商品
            Long inGoods = goodsService.count(goods);
            //仓库中商品
            Long outGoods = allGoods - inGoods;

            map.put("noPayCount",noPayCount);
            map.put("waitPayCount",waitPayCount);
            map.put("PayCount",PayCount);
            map.put("salePayCount",salePayCount);
            map.put("finishPayCount",finishPayCount);
            map.put("todayMoeny",todayMoeny);
            map.put("visitor",visitor);
            map.put("consultation",consultation);
            map.put("orderSuccess",orderSuccess);
            map.put("allGoods",allGoods);
            map.put("inGoods",inGoods);
            map.put("outGoods",outGoods);
            if (!ObjectUtils.isEmpty(company1)) {
                map.put("isCompany",1);
            } else {
                map.put("isCompany",2);
            }
            MsgOut msgOut = MsgOut.success(map);
            return renderJson(msgOut);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    /**
     * 店铺详细信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/companyInfo")
    public String getCompanyInfo(@RequestHeader(value = "headId", required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        Company company = companyService.selectByCompanyStaff(user.getId());
        Company company1 = companyService.selectByUserId(user.getId());
        if (!ObjectUtils.isEmpty(company)) {
            CompanyVO companyVO = new CompanyVO();
            BeanUtils.copyProperties(company,companyVO);
            if(!ObjectUtils.isEmpty(company.getCompanyTypeId())){
                CompanyType companyType = companyTypeService.selectByPK(company.getCompanyTypeId());
                if(!ObjectUtils.isEmpty(companyType.getIndustryId())){
                    CompanyIndustry companyIndustry = companyIndustryService.selectByPK(companyType.getIndustryId());
                    companyVO.setCompanyCommision(companyIndustry.getCompanyCommission());
                    companyVO.setIndustryName(companyIndustry.getName());
                    if(companyIndustry.getId() == 45){
                        companyVO.setIskefu(1);
                    } else {
                        companyVO.setIskefu(0);
                    }
                }
            }
            if (!ObjectUtils.isEmpty(company1)) {
                companyVO.setIsCompany(1);
            } else {
                companyVO.setIsCompany(2);
            }
            MsgOut o = MsgOut.success(companyVO);
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    /**
     * 编辑店铺
     * @param company
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/company", method = RequestMethod.PUT)
    public String update(Company company,@RequestHeader(value="headId",required = false) Long userId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user) && ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company tmp = new Company();
        if (!ObjectUtils.isEmpty(user)) {
            tmp.setUserId(user.getId());
        } else if(!ObjectUtils.isEmpty(userId)){
            tmp.setUserId(userId);
        }
        if (!ObjectUtils.isEmpty(company.getImgHeadPhoto())) {
            String[] imgHeadPhotoList = company.getImgHeadPhoto().split(",");
            if(imgHeadPhotoList.length > 4){
                return this.renderJson(MsgOut.error("Upload 4 pictures at most."));
            }
        }
        List<Company> companyList = companyService.select(tmp);
        if (companyList != null && companyList.size() > 0) {
            company.setCompanyId(companyList.get(0).getCompanyId());
            if (!ObjectUtils.isEmpty(user)) {
                company.setUserId(user.getId());
            } else if(!ObjectUtils.isEmpty(userId)){
                company.setUserId(userId);
            }
            MsgOut o = MsgOut.success(companyService.update(company));
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您没有权限"));
        }
    }

    /**
     * 編輯店鋪（新版）
     * @param company
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/companyUpdate", method = RequestMethod.PUT)
    public String companyUpdate(Company company,@RequestHeader(value="headId",required = false) Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (!ObjectUtils.isEmpty(company.getImgHeadPhoto())) {
            String[] imgHeadPhotoList = company.getImgHeadPhoto().split(",");
            if(imgHeadPhotoList.length > 4){
                return this.renderJson(MsgOut.error("Upload 4 pictures at most."));
            }
        }
        Company company1 = companyService.selectByCompanyStaff(userId);
        if (!ObjectUtils.isEmpty(company1)) {
            company.setCompanyId(company1.getCompanyId());
            MsgOut o = MsgOut.success(companyService.update(company));
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还没有店鋪，赶紧去注册店铺吧"));
        }
    }

    /**
     * 群详情
     * @param companyId
     * @return
     */
    @RequestMapping(value = "/api/wap/Community", method = RequestMethod.GET)
    public String Community(Long companyId){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        Company company = companyService.selectByPK(companyId);
        CompanyAnnouncement companyAnnouncement = new CompanyAnnouncement();
        companyAnnouncement.setCompanyId(companyId);
        List<CompanyAnnouncement> companyAnnouncementList = companyAnnouncementService.select(companyAnnouncement);
        if (!ObjectUtils.isEmpty(companyAnnouncementList)) {
            map.put("companyAnnouncement",companyAnnouncementList.get(0).getNotice());
        } else {
            map.put("companyAnnouncement","");
        }
        map.put("groupNickname",company.getGroupNickname());
        map.put("nickName",sysUserService.selectByPK(user.getId()).getNickname());
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/newSqma", method = RequestMethod.GET)
    public String newSqma(Long companyId,@RequestHeader(value="headId",required = false) Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(companyService.selectByPK(companyId));
        return this.renderJson(o);
    }
}
